import { ActionFormData } from "@minecraft/server-ui";
import { TeamScoreBoardOptions } from "@sapi-game/gameComponent";
import { PlayerGroup } from "@sapi-game/gamePlayer/playerGroup";
import { WereWolfPlayer, WereWolfRole, WereWolfStatus } from "./player";
import { WereWolfNoColor } from "./static";

export interface WereWolfFormOptions {
    title: string;
    body: string;
    getPlayers: () => WereWolfPlayer[];
    buildPlayerName?: (player: WereWolfPlayer) => string;
    onSelect: (player: WereWolfPlayer, selected: WereWolfPlayer) => void;
}

export function showWereWolfForm(
    data: WereWolfFormOptions,
    player: WereWolfPlayer
) {
    if (!player.player) return;
    let form = new ActionFormData().title(data.title).body(data.body);
    const players = data.getPlayers().sort((a, b) => a.no - b.no);
    players.forEach((p) => {
        form = form.button(
            `[${WereWolfNoColor[p.no - 1]}${p.no}号§r]${
                data.buildPlayerName ? data.buildPlayerName(p) : p.name
            }`
        );
    });
    form.show(player.player).then((ans) => {
        if (ans.selection == undefined) return;
        const selected = players[ans.selection];
        data.onSelect(player, selected);
    });
}

export function showRole(players: PlayerGroup<WereWolfPlayer>) {
    players.forEach((p) => {
        switch (p.role) {
            case WereWolfRole.Witch:
                p.title("§5§l女巫", "§5§lThe Witch");
                p.player.playSound("mob.witch.celebrate", { volume: 0.4 });
                break;
            case WereWolfRole.Seer:
                p.title("§b§l预言家", "§b§lThe Seer");
                break;
            case WereWolfRole.Villager:
                p.title("§a§l平民", "§a§lThe Villager");
                p.player.playSound("mob.villager.yes");
                break;
            case WereWolfRole.Hunter:
                p.title("§e§l猎人", "§e§lThe Hunter");
                break;
            case WereWolfRole.Werewolf:
                p.title("§4§l狼人", "§4§lWereWolves");
                break;
            default:
                p.title("你没身份", "怎么混进来的");
        }
    });
}

/**构建玩家名称 */
export function BuildWereWolfPlayerName(player: WereWolfPlayer) {
    return `${WereWolfNoColor[player.no - 1]}[${player.no}号]${player.name}`;
}

export function BuildWereWolfIdOptions(
    players: PlayerGroup<WereWolfPlayer>
): TeamScoreBoardOptions<WereWolfPlayer> {
    return {
        scoreboardName: "WereWolf_id",
        displayName: "§a狼人杀",
        teams: [
            {
                team: players,
                buildName: (p: WereWolfPlayer) => {
                    return `${WereWolfNoColor[p.no - 1]}[${p.no}号]§r${p.name}`;
                },
                teamSort(p1, p2) {
                    return p1.no - p2.no;
                },
                teamFilter(p) {
                    return p.no != 0 && p.status != WereWolfStatus.Dead;
                },
            },
        ],
    };
}
